package com.oilsection.demo.controller;

import cn.hutool.core.util.ObjUtil;
import com.oilsection.demo.controller.req.ZrEventImportReq;
import com.oilsection.demo.controller.req.ZrEventPageQueryReq;
import com.oilsection.demo.controller.req.ZrdImportReq;
import com.oilsection.demo.controller.req.ZrdPageQueryReq;
import com.oilsection.demo.controller.res.ZrEventPageQueryResponse;
import com.oilsection.demo.controller.res.ZrdPageQueryResponse;
import com.oilsection.demo.po.Zrd;
import com.oilsection.demo.service.ZrEventService;
import com.oilsection.demo.service.ZrdService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/zrd")
@RequiredArgsConstructor
@Slf4j
public class ZrdController {
    private final ZrdService zrdService;

    @PostMapping("/getZrdPage")
    @CrossOrigin
    public ZrdPageQueryResponse getZrdPage(@RequestBody ZrdPageQueryReq req) {
        req.setPage(req.getPage() + 1);
        log.info("getZrdPage req:{}", req);
        return zrdService.getZrdPage(req);
    }

    @PostMapping("/import")
    @CrossOrigin
    public void importZrEvent(@RequestBody List<ZrdImportReq> reqs) {
        zrdService.importZrd(reqs);
    }

    // 根据id删除
    @PostMapping("/deleteById/{id}")
    @CrossOrigin
    public boolean deleteZrEvent(@PathVariable Long id) {
        log.info("deleteZrEvent id:{}", id);
        zrdService.deleteZrdById(id);
        return true;
    }

    // 根据id更新
    @PostMapping("/updateById")
    @CrossOrigin
    public boolean updateById(@RequestBody Zrd req) {
        log.info("updateZrd zrd:{}", req);
        String location = req.getLocation();
        if (ObjUtil.isNotEmpty(location)) {
            String regex = "-?\\d+\\.\\d+";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(location);

            if (matcher.find()) {
                req.setXPoint(matcher.group()); // 提取第一个数字
            }
            if (matcher.find()) {
                req.setYPoint(matcher.group()); // 提取第二个数字
            }

        }
        zrdService.updateLocationById(req);
        return true;
    }
}
